/**
 * Copyright 2016 JustWayward Team
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hzf.booklibrary.ui.presenter;

import android.content.Context;

import com.hzf.booklibrary.ReaderApplication;
import com.hzf.booklibrary.api.BookApi;
import com.hzf.booklibrary.api.book.BookListApi;
import com.hzf.booklibrary.base.RxPresenter;
import com.hzf.booklibrary.bean.BookListBean;
import com.hzf.booklibrary.bean.Recommend;
import com.hzf.booklibrary.bean.book.Book;
import com.hzf.booklibrary.ui.contract.RecommendContract;
import com.hzf.booklibrary.utils.LogUtils;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author yuyh.
 * @date 2016/8/3.
 * 继承共性，实现个性getRecommendList()
 */
public class RecommendPresenter extends RxPresenter<RecommendContract.View>
        implements RecommendContract.Presenter<RecommendContract.View> {

    private Context mContext;
    private BookApi bookApi;
    private int class_id = 0;
//    private OkHttpManager okHttpManager = OkHttpManager.getInstance();
//    private OkHttpManager okHttpManager = OkHttpManager.getInstance();

    /**
     * 利用Dragger2的注入依赖(注入的是Module)
     * @param mContext
     * @param bookApi
     */
    @Inject
    public RecommendPresenter(Context mContext, BookApi bookApi) {
        this.mContext = mContext;
        this.bookApi = bookApi;


    }


    public void booksrecommendListByPage(final String page, int pageSize,int id){
//        Subscription rxSubscription = bookApi.booksrecommendListByPage(Integer.parseInt(page),20,id).subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Observer<Recommend>() {
//                    @Override
//                    public void onNext(Recommend recommend) {
//                        if (recommend != null) {
//                            List<Recommend.RecommendBooks> list = recommend.result.items;
//                            if(Integer.parseInt(recommend.result.totalPages) < Integer.parseInt( page)){
//                                list.clear();
//                            }
//
//                            if (list != null && !list.isEmpty() && mView != null) {
////                                mView.showBooksList(list);
//                            }
//                            if(list.isEmpty()){//请求的数据为空
////                                mView.showBooksList(list);
//                            }
//                        }
//                    }
//                    @Override
//                    public void onCompleted() {
//                        mView.complete();
//                    }
//                    @Override
//                    public void onError(Throwable e) {
//                        LogUtils.e("getRecommendList", e.toString());
//                        mView.showError();
//                        ReaderApplication.getsInstance().initIpAdress();//重新获取IP地址
//                    }
//                });
//        addSubscrebe(rxSubscription);
    }

    /**
     * 利用Retrofit2的联网框架获取图书数据
     * 1. 创建OkHttpClient
       2. 创建Retrofit实例
       3. 获取我们写的API interface
       4. 在代码中异步调用

     * 采用RxJava
     */

    public void getBooksList(String token,Integer classNumber,String orgId,Integer page,Integer pageSize) {
        BookListApi.getInstance().getBookList(token,classNumber,orgId,page,pageSize)
        .enqueue(new Callback<BookListBean>() {
            @Override
            public void onResponse(Call<BookListBean> call, Response<BookListBean> response) {
                try {
                    List<BookListBean.DataBean.ItemsBean> items = response.body().getData().getItems();
                    LogUtils.i("接收到的图书列表大小是:"+items.size());
                    List<Book> books = new ArrayList<>();
                    for (int i = 0; i < items.size(); i++) {
                        Book book = new Book();
                        book.id = items.get(i).getId();
                        book.author = items.get(i).getAuthor();
                        book.icon_path = "http://oss-pics-huabei5.oss-cn-huhehaote.aliyuncs.com/"+items.get(i).getIconPath();
                        book.name = items.get(i).getName();
                        book.filetype = items.get(i).getFileType();
                        book.path = "http://oss-pics-huabei5.oss-cn-huhehaote.aliyuncs.com/"+items.get(i).getPath();
                        book.updatetime = items.get(i).getModifydatetime();
                        book.content = items.get(i).getContent();
                        book.isFromSD = true;
                        books.add(book);
                    }
                    LogUtils.i("books的大小是:"+books.size());
                    mView.showBooksList(books);
                    mView.complete();
                }catch (Exception e){
                    e.printStackTrace();
                }


            }

            @Override
            public void onFailure(Call<BookListBean> call, Throwable t) {

            }
        });



       // String key = StringUtils.creatAcacheKey("book-list",itemName);
        //android响应式编程

//        boolean isXiaoPai = DeviceUtils.isXiaoPai(mContext);
//        if(isXiaoPai){
//            Subscription rxSubscription = bookApi.getRecommend(page,classify,id).subscribeOn(Schedulers.io())
//                    .observeOn(AndroidSchedulers.mainThread())
//                    .subscribe(new Observer<Recommend>() {
//                        @Override
//                        public void onNext(Recommend recommend) {
//                            if (recommend != null) {
//                                List<Recommend.RecommendBooks> list = recommend.result.items;
//                                if(Integer.parseInt(recommend.result.totalPages) < Integer.parseInt( page)){
//                                    list.clear();
//                                }
//
//                                if (list != null && !list.isEmpty() && mView != null) {
//                                    mView.showBooksList(list);
//                                }
//                                if(list.isEmpty()){//请求的数据为空
//                                    mView.showBooksList(list);
//                                }
//                            }
//                        }
//                        @Override
//                        public void onCompleted() {
//                            mView.complete();
//                        }
//                        @Override
//                        public void onError(Throwable e) {
//                            LogUtils.e("getRecommendList", e.toString());
//                            mView.showError();
//                            ReaderApplication.getsInstance().initIpAdress();//重新获取IP地址
//                        }
//                    });
//            addSubscrebe(rxSubscription);
//        }else{
//            if(class_id > 0){
//                booksrecommendListByPage(page,20,class_id);
//            }else{
//                String publicMethod = "publicGetClassIdBySerialNo";
//                final String url = String.format("%sPublic/cloud/httpCommandService?cmd=public&cmd_op=%s&serialNo=%s",Constant.API_BASE_URL,publicMethod,DeviceUtils.getMyUUID(mContext));
               // final String url = String.format("http://%s:%s/Public/cloud/httpCommandService?cmd=public&cmd_op=%s&serialNo=%s",ip,ip_port,publicMethod,uuid);

//                okHttpManager.getAsyn(url, new ResultCallBack() {
//                    @Override
//                    public void onResponse(String response) {
//                        try {
//
//                            JSONObject jsonObject = new JSONObject(response);
//                            class_id = jsonObject.getInt("result");
//                            booksrecommendListByPage(page,20,class_id);
//
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                    @Override
//                    public void onError(Request request, Exception e) {
//
//                    }
//                });
//            }
//        }
    }

    @Override
    public void getBooksList(String itemName, String classify, int id) {

    }
}
